/*
 * Dijjer - A Peer to Peer HTTP Cache
 * Copyright (C) 2004,2005 Change.Tv, Inc, Mathias De Maré
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package dijjer.io.comm;

import java.net.DatagramPacket;

import dijjer.AbstractFactory;
import dijjer.updater.ResourceManager;
import dijjer.util.logging.Logger;

public class WebMulticastSocketManager extends AbstractMulticastSocketManager {

	public WebMulticastSocketManager(int listenPort) throws Exception {
		super(listenPort);
	}

	protected boolean loop() throws InterruptedException {
		Message m = null;
		try {
			m = AbstractFactory.getFactory().getResourceManager().receiveMC(_listenPort);
		}
		catch(Exception e) {
			//e.printStackTrace();
			Logger.error("Couldn't parse packet");
		}

		// Check for matched _filters
		if (m != null) {
			checkFilters(m);
		}
		return true;
	}

	public String toString() {
		// TODO Auto-generated method stub
		return "WebMulticastSocketManager";
	}
	
	private void checkFilters(Message m) {
		WebPeer wp = (WebPeer) m.getSource();
		// No message, or one we sent to the multicast group
		if ((m == null)
			|| (m.getSpec().equals(DMT.whoAreYou)
				&& (wp.getPort() == AbstractFactory.getFactory().getResourceManager().mcastPort)
				&& wp.getAddress().equals(
						((WebPeer) AbstractFactory.getFactory().getRoutingTable().getPeer()).getAddress()))) {
			return;
		}

		if (m.getSpec().equals(DMT.ping)
			|| m.getSpec().equals(DMT.pong)
			|| m.getSpec().equals(DMT.packetTransmit)
		) {
			Logger.debug("" + (System.currentTimeMillis() % 60000) + " " + _listenPort + " <- "
					+ m.getSource() + " : " + m);
		} else {
			Logger.info("" + (System.currentTimeMillis() % 60000) + " " + _listenPort + " <- "
					+ m.getSource() + " : " + m);
		}
		
		if (_dispatcher == null) {
			setDispatcher(Dispatcher.getDispatcher());
		}

        boolean matched = MessageFilter.checkFilters(m);
        // Feed unmatched messages to the dispatcher
		if (!matched && (_dispatcher != null)) {
			try {
				matched = _dispatcher.handleMessage(m);
			} catch (Exception e) {
				Logger.error("Error handling message: "+ m, e);
			}
		}
		// Keep the last few _unclaimed messages around in case the intended receiver isn't receiving yet
		if (!matched) {
			Logger.info("Received unclaimed message "+m+", adding to unclaimed pile");
            MessageFilter.addUnclaimed(m);
		}
	}

	public static void init(int externalListenPort)
		throws Exception
	{
		WebMulticastSocketManager usm = new WebMulticastSocketManager(externalListenPort);
		AbstractMulticastSocketManager.init(usm);
	}

}
